package cn.bs.allensocket;

import cn.bs.socket.server.Dgram;

import java.io.IOException;
import java.net.*;

import static cn.bs.allensocket.AllenDgram.toDataGram;

/**
 * Created by Allen on 2014/11/1.
 */
public class AllenDatagramSocketClient implements Runnable {
    static int port = 7200;
    private byte[] buf = new byte[1000];
    private DatagramPacket dp = new DatagramPacket(buf,buf.length);
    private DatagramSocket socket;

    private InetAddress address;
    private int id;

    public AllenDatagramSocketClient(int identifier ) throws UnknownHostException,SocketException{
        socket = new DatagramSocket();
        id = identifier;
        address = InetAddress.getByName(null);

    }
    @Override
    public void run(){
        try{
            for(int k= 0;k<25;k++){
                String msg ="Client:" + id + ":msg-" + k;
                System.out.println(address.getHostName());
                socket.send(toDataGram(msg, InetAddress.getLocalHost(), port));
                socket.receive(dp);
                String rcvd = "Client # " + id + ",rcvd from " + dp.getAddress() + "," + dp.getPort() + Dgram.toString(dp);
                System.out.println(rcvd);

            }
            socket.close();
        }catch(IOException e){
            e.printStackTrace();
        }


    }

}
